<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>按下键盘时将响应体内容放入框中</title>
    <style>
        div{
        width: 200px;
        height: 200px;
        border: 1px solid #ccc;
    }</style>
</head>
<body>
<div id="result"></div>
<script>
    var div=document.querySelector('#result');
    window.addEventListener('keydown',function (){
        const xhr=new XMLHttpRequest();
        //方法2 自动转成obj
        xhr.responseType='json';
        xhr.open('get','http://127.0.0.1:5050/json-server');
        xhr.send();
        xhr.addEventListener('readystatechange',function (){
            if(xhr.readyState===4){
                if(xhr.status>=200&&xhr.status<300){
                    // 方法1 手动转成obj
                    // var data=JSON.parse(xhr.response);
                    // div.innerHTML=data.name;
                    div.innerHTML=xhr.response.name;
                }
            }
        })
    })
</script>
</body>
</html>